const fs = require('fs')
const axios = require('axios')
const { getRedisMap, setRedisMap } = require('../dataBase/redis')
const { appid, secret } = require('../config/wechat')
const { wechatAccessTokenUrl } = require('./urlList')


/** 获取微信公众号accessToken */
const getAccessToken = async (accountName = "testAccount") => {
    // 获取redis中的accessToken
    const localAccessToken = await getRedisMap(accountName, "weChatToken")
    let resAccessToken = ''
    let isExpired = false
    if (localAccessToken) {
        const { access_token, expireTime } = JSON.parse(localAccessToken)
        const nowTime = new Date().getTime()
        isExpired = nowTime >= expireTime
        resAccessToken = !isExpired ? access_token : ''
    }

    if (!localAccessToken || isExpired) {
        await updateAccessToken(accountName)
        await getAccessToken(accountName)
    }

    return resAccessToken
}

/** 刷新微信公众号accessToken */
const updateAccessToken = async (accountName) => {
    try {
        const res = await axios.get(`${wechatAccessTokenUrl}`, {
            params: {
                appid,
                secret,
                grant_type: 'client_credential'
            }
        })
        console.log('打印***res', res.data)
        if (res.data) {
            const { access_token, expires_in } = res.data
            const expireTime = new Date().getTime() + expires_in * 1000
            const accessToken = JSON.stringify({ access_token, expireTime, expires_in })
            await setRedisMap(accountName, "weChatToken", accessToken)
        }
    } catch (error) {
        setRedisMap(accountName, "weChatToken", '')
    }

}
module.exports = {
    getAccessToken
}